package class04;

/**
 * @Auther: xw
 * @Create: 2022/3/11 16:27
 * @Description: 用链表实现队列和栈
 */
public class LinkedListToQueueAndStack {
    public static class Node<V>{
        public V value;
        public Node<V> next;

        public Node(V v){
            this.value  =v;
            next = null;
        }

    }

    /**
     * 队列
     * @param <V>
     */
    public static class MyQueue<V> {
        private  Node<V> head;
        private Node<V> tail;
        private int size;

        public MyQueue(){
            head =null;
            tail = null;
            size = 0;
        }

        public boolean isEmpty(){
            return size == 0;
        }

        /***
         * 入队
         * @param value
         */
        public void offer(V value){
            Node<V> cur = new Node<V>(value);
            if(null == tail){
                head = cur;
                tail = cur;
            }else{
                tail.next = cur;
                tail = cur;
            }
            size ++;
        }
        public V  poll(){
            V ans = null;
            if (head != null){
                ans = head.value;
                head = head.next;
                size --;
            }
            if(head == null){
                tail = null;
            }
            return ans;
        }

        public V peak(){
            V ans = null;
            if(head != null){
                ans = head.value;
            }
            return ans;
        }

    }
    public  static  class MyStack<V>{
        private Node<V> head;
        private int size;
        public MyStack(){
            head = null;
            size  = 0;
        }
        public boolean isEmpty(){
            return size == 0;
        }
        public int size() {
            return size;
        }
        public void push(V value){
            Node<V> cur = new Node<V>(value);
            if(head == null){
                head = cur;
            }else{
                head.next = cur;
                head = cur;
            }
            size++;
        }
        public V pop(){
            V ans = null;
            if(null != head){
                ans = head.value;
                head = head.next;
                size--;
            }
            return ans;
        }
        public V peek() {
            return head != null ? head.value : null;
        }

    }
}
